package com.example.lotterysystem.dao.handler;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.example.lotterysystem.dao.dataobject.Encrypt;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(Encrypt.class)//指定java类型
@MappedJdbcTypes(JdbcType.VARCHAR)//指定jdbc类型
public class EncryptTypeHandler extends BaseTypeHandler<Encrypt> {
    private final byte[]KEY="123456789abcdefg".getBytes(StandardCharsets.UTF_8);


    /**
     * 设置参数
     * @param preparedStatement   sql预编译的对象
     * @param i  参数位置
     * @param encrypt 参数
     * @param jdbcType jdbc类型
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Encrypt encrypt, JdbcType jdbcType) throws SQLException {
if(encrypt==null||encrypt.getValue()==null){
    preparedStatement.setString(i,null);
    return;
}

        System.out.println("加密前:"+encrypt.getValue());
        AES aes= SecureUtil.aes(KEY);
String str=aes.encryptHex(encrypt.getValue());
        System.out.println("加密后:"+str);
preparedStatement.setString(i,str);
    }

    /**
     * 通过列名获取结果
     * @param resultSet  结果集
     * @param s 索引名
     * @return
     * @throws SQLException
     */

    @Override
    public Encrypt getNullableResult(ResultSet resultSet, String s) throws SQLException {
        System.out.println("解密前"+resultSet.getString(s));
        return decrypt(resultSet.getString(s));
    }

    /**
     * 通过列索引获取结果
     * @param resultSet
     * @param i
     * @return
     * @throws SQLException
     */

    @Override
    public Encrypt getNullableResult(ResultSet resultSet, int i) throws SQLException {
        System.out.println("解密前"+resultSet.getString(i));
        return decrypt(resultSet.getString(i));
    }

    /**
     * 通过存储过程获取结果
     * @param callableStatement
     * @param i
     * @return
     * @throws SQLException
     */

    @Override
    public Encrypt getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        System.out.println("解密前"+callableStatement.getString(i));
        return decrypt(callableStatement.getString(i));
    }

private Encrypt decrypt(String str){
        if(!StringUtils.hasText(str)){
            return null;
        }
        return new Encrypt(SecureUtil.aes(KEY).decryptStr(str));
}
}
